<?php 
/**
 * Access data on Chicagogasprices.com and store in DB
 * 
 * @author hliu0080
 *
 */
include('../lib/simple_html_dom.php');

class gasApi
{
	private $urlA = '';
	private $urlB = '';
	private $urlC = '';
	private $gasPrices = array();
	
	public function __construct($area='Chicago+-+Central', $time_limit='24'){
		$this->urlA = "http://www.chicagogasprices.com/GasPriceSearch.aspx?fuel=A&area=$area&tme_limit=$time_limit";
		$this->urlB = "http://www.chicagogasprices.com/GasPriceSearch.aspx?fuel=B&area=$area&tme_limit=$time_limit";
		$this->urlC = "http://www.chicagogasprices.com/GasPriceSearch.aspx?fuel=C&area=$area&tme_limit=$time_limit";
	}	
	
	/**
	 * Parse raw gas data
	 */
	public function fetchGasPrices(){
		$rows = array();
		// TODO: catch exceptions when fails
		$html = file_get_html($this->urlA);
		if(is_null($html)){
			throw new Exception('Error initializing DOM object');
			return false;
		}
		foreach($html->find("tr[sm]") as $tr){
			$row = array(
					'name' => $this->_parseName($tr),
					'address' => $this->_parseAddress($tr),
					'area' => $this->_parseArea($tr),
					'time' => $this->_parseDatetime($tr),
					'regular' => $this->_parsePrice($tr),
					'midgrade' => NULL,
					'premium' => NULL
			);
			array_push($rows, $row);
		}
		
		$html = file_get_html($this->urlB);
		foreach($html->find("tr[sm]") as $tr){
			foreach($rows as $key=>$row){
				if($this->_parseAddress($tr)==$row['address'] && $this->_parseName($tr)==$row['name']){
					$rows[$key]['midgrade'] = $this->_parsePrice($tr);
					break;
				}
			}
		}
		
		$html = file_get_html($this->urlC);
		foreach($html->find("tr[sm]") as $tr){
			foreach($rows as $key=>$row){
				if($this->_parseAddress($tr)==$row['address'] && $this->_parseName($tr)==$row['name']){
					$rows[$key]['premium'] = $this->_parsePrice($tr);
					break;
				}
			}
		}
		
		$this->gasPrices = $rows;
		return true;
	}
	
	
	/**
	 * Store parsed gas data in DB
	 */
	public function saveGasPrices($batch_id){
		foreach($this->gasPrices as $g){
			$gas = new Gas();
			$gas->setName($g['name']);
			$gas->setAddress($g['address']);
			$gas->setRegular($g['regular']);
			$gas->setMidgrade($g['midgrade']);
			$gas->setPremium($g['premium']);
			$gas->setReportedDate($g['time']);
			$gas->setBatchId($batch_id);
			$gas->save();
		}
	}
	
	/**
	 * Created a batch record and return batch_id
	 * @return number
	 */
	public function createBatch($area){
		$batch = new Batch();
		$batch->setArea($area);
		$batch->save();
		return $batch->getId();
	}
	
	/**
	 * Cleanup price from raw fetch
	 *
	 * @param unknown $tr
	 * @return mixed
	 */
	private function _parsePrice($tr){
		$price = "";
		foreach($tr->find("div[class=sp_p]", 0)->find("div") as $p){
			$class = $p->class;
			$price .= $class[1];
		}
		$price = str_replace('d', '.', $price);
		return $price;
	}
	
	/**
	 * Cleanup station name from raw fetch
	 *
	 * @param unknown $tr
	 * @return string
	 */
	private function _parseName($tr){
		$name = $tr->find("dl[class=address]", 0)->first_child()->first_child();
		if($name->hasChildNodes()){
			$name = $name->first_child()->src;
			$name = ($name=="http://mymarathonstation.com/images/213/price-listing-ad-brand-logo.png"?"Marathon":$name);
		}else{
			$name = $name->innertext;
		}
		$name = htmlspecialchars_decode($name);
		return $name;
	}
	
	/**
	 * Cleanup station address from raw fetch
	 *
	 * @param unknown $tr
	 * @return string
	 */
	private function _parseAddress($tr){
		return htmlspecialchars_decode($tr->find("dl[class=address]", 0)->first_child()->next_sibling()->innertext);
	}
	
	/**
	 * Cleanup station area from raw fetch
	 *
	 * @param unknown $tr
	 */
	private function _parseArea($tr){
		return $tr->find("a[class=p_area]", 0)->innertext;
	}
	
	/**
	 * Cleanup datetime from raw fetch to date("Y-m-d H:i:s")
	 *
	 * @param unknown $tr
	 * @return string
	 */
	private function _parseDatetime($tr){
		$report_date = $tr->find("div[class=tm]", 0)->title;
		$report_datetime = explode(" ", $report_date);
		
	
		$today = date("D Y-m-d");
		$today = explode(' ', $today);
		if($report_datetime[0] != $today[0]){
			$yesterday = date("Y-m-d", time() - 60 * 60 * 24);
// 			$ret = "$yesterday $report_datetime[1] $report_datetime[2]";
			$ret =  $yesterday . " " . date("H:i:s", strtotime("$report_datetime[1] $report_datetime[2]"));
		}else{
// 			$ret = "$today[1] $report_datetime[1] $report_datetime[2]";
			$ret = $today[1] . " " . date("H:i:s", strtotime("$report_datetime[1] $report_datetime[2]"));
		}
		
		return $ret;
	}
	
	/**
	 * Getter & Setter
	 * 
	 * @return multitype:
	 */
	public function getPrices(){
		return $this->gasPrices;
	}
	
}